package com.qf.openapi.web.master.filter;

import com.qf.openapi.web.master.utils.Constants;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/logout")
@Slf4j
public class LogoutFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("==============LogoutFilter 初始化成功===============");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        final HttpServletRequest req = (HttpServletRequest) request;

        final HttpServletResponse resp = (HttpServletResponse) response;

        // 注销当前用户
        log.debug("删除session中的user对象");

        final HttpSession session = req.getSession();
        session.setAttribute(Constants.SESSION_USER_KEY,null);

        log.debug("删除浏览器中的 usertoken cookie");
        final Cookie cookie = new Cookie(Constants.USER_TOKEN, "usertoken");
        cookie.setPath("/");
        cookie.setMaxAge(0);

        resp.addCookie(cookie);

        // 重定向到登陆页面
        resp.sendRedirect("/login.html");

//        chain.doFilter(request,response);  //放行请求
    }

    @Override
    public void destroy() {
        log.debug("==============LogoutFilter destroy ===============");
    }
}
